package com.unsiv.blplayer;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.unsiv.blplayer.playtools.MP3Logic;
import com.unsiv.blplayer.playtools.Protocol;
import com.unsiv.blplayer.util.MyFileHelper;
import com.unsiv.blplayer.util.MyMediaHelper;

/**
 * 
 * @author fanzhen
 * @time 12:20:47 PM Sep 25, 2011
 * @email fanzhen.meng@gmail.com
 */
public class BluetoothPenActivity extends Activity {
	private static final String TAG = "BluetoothPenActivity";
	private static final int REQUEST_CONNECT_DEVICE = 1;
	private static final int REQUEST_ENABLE_BLUETOOTH = 2;
	BroadcastReceiver commandReceiver;
	IntentFilter commandFilter;
	private TextView mTitle;
	private BluetoothAdapter mBluetoothAdapter;
	private Button b_quit;
	private TextView tv1;
	private Button button1;
	private Button button2;
	private Button button3;
	private Button button4;
	private Button button5;
	private Button button6;
	private Button button7;
	private Button button8;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.custom_title);
		MyFileHelper.init();//初始化数据
		MP3Logic.context = getApplicationContext();
		mTitle = (TextView) findViewById(R.id.title_left_text);
		mTitle.setText(R.string.app_name);
		mTitle = (TextView) findViewById(R.id.title_right_text);
		b_quit = (Button) findViewById(R.id.b_quit);
		tv1 = (TextView) findViewById(R.id.tv1);
		button1 = (Button) findViewById(R.id.button1);
		button2 = (Button) findViewById(R.id.button2);
		button3 = (Button) findViewById(R.id.button3);
		button4 = (Button) findViewById(R.id.button4);
		button5 = (Button) findViewById(R.id.button5);
		button6 = (Button) findViewById(R.id.button6);
		button7 = (Button) findViewById(R.id.button7);
		button8 = (Button) findViewById(R.id.button8);
		b_quit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				MyMediaHelper.playFromAbsolutePath(MyFileHelper.G_Mp3Folder+"My Love.mp3");
			}
		});
		button2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
			}
		});
		button3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

			}
		});
		button4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				byte[] demoData = Protocol.CreateDemoData(Protocol.OIDPre,
						1000201);
				StringBuilder sb = new StringBuilder(tv1.getText());
				sb.append(Protocol.OIDPre);
				sb.append("1000201");
				sb.append("\n");
				tv1.setText(sb);
				Protocol.RecvData(demoData);
			}
		});
		button5.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(MyMediaHelper.mp.isPlaying()){
					MyMediaHelper.mp.reset();
				}
				InputStream is = getResources().openRawResource(R.raw.ihaveadream);
				try {
					int length = is.available();
					Log.i(TAG, String.valueOf(length));
					byte[] mp3SoundByteArray =  new byte[2073606];
					is.skip(3073605);
					is.read(mp3SoundByteArray,0,2073605);
					MyMediaHelper.playFromByteArray(mp3SoundByteArray);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		button6.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

			}
		});
		button7.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

			}
		});
		button8.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

			}
		});
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.device_not_found,
					(ViewGroup) findViewById(R.id.device_notfound));
			new AlertDialog.Builder(this)
					.setTitle("BlueToothStatus")
					.setView(layout)
					.setPositiveButton("退出",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							}).show();
		} else {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
		}
		MyMediaHelper.mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
			@Override
			public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
		});
		MyMediaHelper.mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
			@Override
			public void onVideoSizeChanged(MediaPlayer arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
		});
		MyMediaHelper.mp.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				mp.reset();
			}
		});
		MyMediaHelper.mp.setOnInfoListener(new OnInfoListener() {
			@Override
			public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
				return false;
			}
		});
	}

	@Override
	public void onResume() {
		if (commandFilter == null)
			commandFilter = new IntentFilter(BluetoothPenService.COMMAND_COMING);
		if (commandReceiver == null)
			commandReceiver = new BroadcastReceiver() {
				@Override
				public void onReceive(Context context, Intent intent) {
					String command = intent
							.getStringExtra(BluetoothPenService.COMMAND_TAG);
					Log.i(TAG, "msg from service.............." + command);
				}
			};
		registerReceiver(commandReceiver, commandFilter);
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (commandReceiver != null) {
			unregisterReceiver(commandReceiver);
			commandReceiver = null;
		}
		if (commandFilter != null)
			commandFilter = null;
		super.onDestroy();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				// Get the device MAC address
				String name = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_NAME);
				String address = data.getExtras().getString(
						DeviceListActivity.EXTRA_DEVICE_ADDRESS);
				// Get the BLuetoothDevice object
				BluetoothDevice device = mBluetoothAdapter
						.getRemoteDevice(address);
				UUID uuid = UUID
						.fromString("00001101-0000-1000-8000-00805f9b34fb");
				try {
					if (null != device.createRfcommSocketToServiceRecord(uuid)) {
						tv1.setText("已连接到" + name);
						startService(new Intent(this, BluetoothPenService.class));
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			break;
		case REQUEST_ENABLE_BLUETOOTH:
			if (resultCode == Activity.RESULT_OK) {
				Intent serverIntent = new Intent(this, DeviceListActivity.class);
				startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			} else {
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				// finish();
			}
		}
	}
}